package top.infopub.job.flow.service.impl;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.infopub.job.flow.service.OAFlowService;
import top.infopub.job.hr.service.StaffInfoService;
import top.infopub.job.sys.service.OperatorService;
import top.infopub.job.util.OAUtil;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.sys.Operator;

import java.util.HashMap;
import java.util.Map;

@Service
public class OAFlowServiceImpl implements OAFlowService {

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private OperatorService operatorService;

    @Override
    public String sendOAToDo(String title, String sendUserId, String toUserId, String srcBizTable, String srcBizSguid, String proCode) throws Exception {
        // http://localhost:8080/mgr/sso?date=1609983279802&backUrl=http://localhost:8080/mgr/main&token=1937694_421ef99d1295c409d4dbf2e742352a5c
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = attributes.getRequest();
//        String contextPath = request.getContextPath();
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + contextPath + "/";
        String basePath = "http://proxy.zhongnangroup.cn/ZNinvestment/";
        String backUrl = basePath + bizControllerMapping(srcBizTable, srcBizSguid, proCode);

        StaffInfo createStaffInfo = getStaffInfoById(dealNameOf(sendUserId).getHrStaffId());
        StaffInfo toStaffInfo = getStaffInfoById(dealNameOf(toUserId).getHrStaffId());
        Map<String, String> oaMap = new HashMap<>();
        oaMap.put("titile", title);
        oaMap.put("createbyname", createStaffInfo.getName());
        oaMap.put("createbycode", createStaffInfo.getCode());
        oaMap.put("toname", toStaffInfo.getName());
        oaMap.put("tocode", toStaffInfo.getCode());
        oaMap.put("type", "znjt");
        oaMap.put("url", basePath + "mgr/sso?backUrl=" + backUrl);//处理公文页面链接
        oaMap.put("company", toStaffInfo.getOrgName());//公司名称
        JSONObject str = OAUtil.erpTodo(oaMap);
        boolean success = str.getBoolean("success");
        String oaId = "";
        if (success) {
            oaId = str.getString("id");
            if (StringUtils.isEmpty(oaId)) {
//                throw new Exception("发起OA待办失败，请联系管理员");
            }
        } else {
//            throw new Exception("发起OA待办失败，请联系管理员");
        }
        return oaId;
    }

    @Override
    public boolean finishOA(String id) throws Exception {
        JSONObject str = OAUtil.finishOA(id);
        boolean success = str.getBoolean("success");
        if (success) {
            return success;
        } else {
//            throw new Exception("处理OA待办失败，请联系管理员");
        }
        return false;
    }

    private Operator dealNameOf(String checkUserId) {
        Operator opt = operatorService.selectByPrimaryKey(checkUserId);
        if (opt == null) {
            return new Operator();
        } else {
            return opt;
        }
    }

    private StaffInfo getStaffInfoById(String staffId) {
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(staffId);
        if (staffInfo == null) {
            return new StaffInfo();
        } else {
            return staffInfo;
        }
    }

    /**
     * 生成 对应 跳转到各业务审核页面的controller方法
     *
     * @param srcBizTable
     * @return
     * @see
     */
    private String bizControllerMapping(String srcBizTable, String srcBizSguid, String proCode) {
        StringBuilder result = new StringBuilder();
        // 如把PRO_MASTER_INFO 转成 masterInfo
        String[] split = srcBizTable.split("_");
        StringBuilder buffer = new StringBuilder();
        buffer.append(split[1].toLowerCase());
        for (int i = 2; i < split.length; i++) {
            String lowerCaseSplit = split[i].toLowerCase();
            String firstUpperChar = (lowerCaseSplit.charAt(0) + "").toUpperCase();
            buffer.append(firstUpperChar + lowerCaseSplit.substring(1));
        }
        result.append(buffer);
        // 【注意】：所有业务表单，跳转到审核页面必须统一命名：toDealOrDetail
        result.append("/toDealOrDetail?id=");
        result.append(srcBizSguid);
        result.append("&processDealWith=y&proCode=");
        result.append(proCode);
        result.append("&times=");
        result.append(System.currentTimeMillis());
        return result.toString();
    }
}
